package com.brush.framework.web.service;

import com.brush.app.domain.AppUser;
import com.brush.app.service.AppUserService;
import com.brush.common.core.domain.resp.AppUserDetails;
import com.brush.common.core.domain.resp.AppUserResp;
import com.brush.common.enums.UserStatus;
import com.brush.common.exception.ServiceException;
import com.brush.common.utils.MessageUtils;
import com.brush.common.utils.ip.AddressUtils;
import com.brush.common.utils.ip.IpUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;

/**
 * 手机端用户登录和权限的业务逻辑实现
 */
@Log4j2
@Service
public class AppUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AppUserService appUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AppUser dbUser = this.appUserService.findByPhone(username);

        if (Objects.isNull(dbUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }

        if (UserStatus.DELETED.getCode().equals(dbUser.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }

        if (UserStatus.DISABLE.getCode().equals(dbUser.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }


        AppUserResp appUserResp = new AppUserResp();
        appUserResp.setId(dbUser.getUserId());
        appUserResp.setArea(dbUser.getArea());
        appUserResp.setAvatar(dbUser.getAvatar());
        appUserResp.setLevelId(dbUser.getLevelId());
        appUserResp.setNickName(dbUser.getNickName());
        appUserResp.setPhone(dbUser.getPhone());
        appUserResp.setSex(dbUser.getSex());
        appUserResp.setPassword(dbUser.getPassword());
        appUserResp.setOpenId(dbUser.getOpenId());
        appUserResp.setScore(dbUser.getScore());


        //返回对象
        AppUserDetails appUserDetails = new AppUserDetails(appUserResp, new HashSet<String>());
        appUserDetails.setIpaddr(IpUtils.getIpAddr());
        appUserDetails.setLoginLocation(AddressUtils.getRealAddressByIP(appUserDetails.getIpaddr()));
        return appUserDetails;
    }
}
